# utils/exception.py
from rest_framework.response import Response
from rest_framework.views import exception_handler as drf_exception_handler
from rest_framework import status
from django.db import DatabaseError
import logging

logger = logging.getLogger(__name__)


def custom_exception_handler(exc, context):
    """
    自定义全局异常处理器
    :param exc: 异常对象
    :param context: 抛出异常的上下文
    :return: Response 响应对象
    """
    # 调用 DRF 默认异常处理
    response = drf_exception_handler(exc, context)

    # 记录异常日志
    logger.error(f"Exception occurred: {str(exc)}", exc_info=True)

    if response is None:
        if isinstance(exc, DatabaseError):
            response = Response(
                {'message': '服务器内部错误', 'detail': str(exc)},
                status=status.HTTP_507_INSUFFICIENT_STORAGE
            )
        elif isinstance(exc, ConnectionError):
            response = Response(
                {'message': '网络连接异常'},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )
        elif isinstance(exc, KeyError):
            response = Response(
                {'message': f'缺少必要参数: {str(exc)}'},
                status=status.HTTP_400_BAD_REQUEST
            )
        else:
            # 其他未处理的异常统一返回 500
            response = Response(
                {'message': '服务器内部错误', 'detail': str(exc)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )

    return response
